import { IPrivacyResponse, IResponseSuccess, IShopUserLogin, IShopUserLoginUserInfo, ISubscribeMessagePromise } from "@/typing";
import Taro from "@tarojs/taro";
import { handleAgreementPrivacy, handleAgreementService, handleLoginAjax } from "./service";
import { AJAX_UPLOAD_API_URL } from "./serviveApi";
import {  PAGE_PATH, RESPONSE_CODE, STORE_KEY, SUBSCRIBE_NOTICE } from "./config";

interface DataItem {
  value: string;
  label: string;
  children?: DataItem[];
}
// 导出一个函数，用于获取设备信息
export const handleDeciveInfo = () => {
  // 获取窗口信息
  const windowInfo = Taro.getWindowInfo() as any;
  // 获取菜单按钮信息
  const menuButtonInfo = Taro.getMenuButtonBoundingClientRect() as any;
  // 获取状态栏高度
  const statusBarHeight = windowInfo.statusBarHeight;
  // 获取导航栏高度
  const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2 + statusBarHeight;

  // 获取底部安全区域高度
  // console.log(windowInfo)
  const bottomSafeHeight = windowInfo.screenHeight - windowInfo.safeArea?.height - statusBarHeight;
  // 返回设备信息
  return {
    statusBarHeight,
    navBarHeight,
    bottomSafeHeight
  }
}
//小程序状态栏高度、导航栏高度

export function showToast(title: string) {
  if(!title) return
  Taro.showToast({
    title: title,
    icon: 'none',
    duration: 1000
  });
}

function isLegalPath(url: string) {
  return Object.values(PAGE_PATH).join(',').indexOf(url.split('?')[0]) > -1;
}

export function goNavigatePage(url: string) {
  const _isLegalPath = isLegalPath(url);
  if (url && _isLegalPath) {
    Taro.navigateTo({
      url
    });
  } else {
    // 路径错误
    showToast('页面正在开发中，敬请期待');
  }
}

export function handleInitLogin(): Promise<IShopUserLoginUserInfo> {
  return new Promise((resolve) => {
    // const userId = Taro.getStorageSync(STORE_KEY.USER_ID) || ''
    const storePhone = Taro.getStorageSync(STORE_KEY.PHONE) || '';
    // console.log(userId, storePhone)
    if (storePhone) return;
    Taro.login({
      success: async (res) => {


        if (res.code) {
          const loginRes = await handleLoginAjax(res.code) as IResponseSuccess<IShopUserLogin>
          if (loginRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {

            if (loginRes.data.code === RESPONSE_CODE.SUCCESS) {

              const loginData = loginRes.data.data.userInfo
              Taro.setStorageSync(STORE_KEY.USER_INFO, JSON.stringify(loginData))
              Taro.setStorageSync(STORE_KEY.TOKEN, loginData.token)
              Taro.setStorageSync(STORE_KEY.USER_ID, loginData.id)
              resolve(loginData)
            } else if (loginRes.data.code === RESPONSE_CODE.ERROR) {
              throw new Error("请求异常");

            }
            else {
              showToast(loginRes.data.msg)
            }

          }
          else {
            showToast('服务器错误')
          }

        } else {
          showToast(res.errMsg)

        }
      }
    })
  })
}


export function handleCommonUpload(filePath: string): Promise<any> {
  return new Promise((resolve, reject) => {

    Taro.showLoading({
      title: '上传中...',
      mask: true
    })
    const token = Taro.getStorageSync(STORE_KEY.TOKEN) || ''

    Taro.uploadFile({
      url: AJAX_UPLOAD_API_URL,
      filePath: filePath,
      header: {
        'ba-shopuser-token': token
      },
      name: 'file',
      success(result) {
        console.log(result)

        Taro.hideLoading({

        })
        if (result.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
          const uplloadRes = JSON.parse(result.data)

          if (uplloadRes.code === RESPONSE_CODE.SUCCESS) {
            showToast(uplloadRes.msg)

            const fileUrl = `${uplloadRes.data.file.url}`

            resolve({
              code: uplloadRes.code,
              fileUrl
            })

          } else if (uplloadRes.code === RESPONSE_CODE.LOGIN_EXPIRE || uplloadRes.code === RESPONSE_CODE.LOGIN_NEED) {
            resolve({
              code: uplloadRes.code,
              avatarUrl: ''
            })

            // resolve('')
          } else if (uplloadRes.code === RESPONSE_CODE.ERROR) {
            throw new Error("请求异常");

          }
          else {
            showToast(uplloadRes.msg)


          }

        } else {
          // showToast('上传失败')
          resolve('')
        }
      },
      fail() {
        resolve('')
        Taro.hideLoading()

      }
    })
  })
}

export const handleInitStoreBaseInfo = () => {
  const storeBaseUserInfo = JSON.parse(Taro.getStorageSync(STORE_KEY.BASE_USER_INFO) || '{}')

  return storeBaseUserInfo
}
export function goDetail(url: string) {
  const _isLegalPath = isLegalPath(url);
  if (url && _isLegalPath) {
    Taro.navigateTo({
      url
    });
  } else {
    // 路径错误
    showToast('页面正在开发中，敬请期待');
  }
}


export function toPage(key) {
  console.log(PAGE_PATH[key])

  Taro.navigateTo({
    url: PAGE_PATH[key]
  });
}

export const handleCleanStore = () => {
  Taro.removeStorageSync(STORE_KEY.PHOTO_LIST)
  Taro.removeStorageSync(STORE_KEY.VIDEO_URL)
  Taro.removeStorageSync(STORE_KEY.TOPIC)
  Taro.removeStorageSync(STORE_KEY.README)
  Taro.removeStorageSync(STORE_KEY.JOB_ID_DESC)
  Taro.removeStorageSync(STORE_KEY.JOB_ID_LIST)
  Taro.removeStorageSync(STORE_KEY.BASE_USER_INFO)
  Taro.removeStorageSync(STORE_KEY.ADD_SERVICE_TYPE)
  Taro.removeStorageSync(STORE_KEY.ADD_SERVICE_TYPE_DESC)
  Taro.removeStorageSync(STORE_KEY.NOT_LOAD)
  Taro.removeStorageSync(STORE_KEY.EDIT_NICKNAME)
  Taro.removeStorageSync(STORE_KEY.EDIT_AVATAR)
  // Taro.removeStorageSync('chat-service-wxapp-coatIndex')


}
export const handleCleanAllStore = () => {
  handleCleanStore();
  Taro.removeStorageSync(STORE_KEY.TOKEN)
  Taro.removeStorageSync(STORE_KEY.PHONE)

  Taro.removeStorageSync(STORE_KEY.USER_ID)
  Taro.removeStorageSync(STORE_KEY.USER_INFO)

  Taro.removeStorageSync(STORE_KEY.USER_PROFILE_STATUS)
  Taro.removeStorageSync(STORE_KEY.CHANNEL_CATEGORIE_LIST)

  Taro.removeStorageSync(STORE_KEY.ORIGIN_PHOTO_LIST)



  // Taro.removeStorageSync('chat-service-wxapp-coatIndex')


}
export const arraysAreEqual = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return true; // 长度不一致
  }

  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) {
      return true; // 找到不同的元素
    }
  }
  return false; // 所有元素都相同
}
/**
 * 
 * @param arr1 新数据
 * @param arr2 旧数据
 * @returns 
 */
export const photosAreEqual = (arr1, arr2) => {
  let editType = 2
  if (arr1.length === arr2.length) {
    editType = 1;
    for (let i = 0; i < arr1.length; i++) {

      if (arr2[i] !== arr1[i]) {
        return {
          type: editType,
          flag: true
        }
        //所有元素都相同
      }
    }
  } else {
    editType = 2;
    for (let i = 0; i < arr1.length; i++) {
      if (!arr2.includes(arr1[i])) {
        return {
          type: editType,
          flag: true
        }
        // 找到不同的元素
      }
    }
  }


  return {
    type: editType,
    flag: false
  }
}

export const handleLoginCallback = async (callback: () => void) => {
  Taro.removeStorageSync(STORE_KEY.PHONE)
  await handleInitLogin().then(async () => {
    callback()
  })
}

const formatData = (data: any[]): DataItem[] => {
  return data.map(item => {
    const children = item.children ? formatData(item.children) : undefined;
    return {
      value: item.code,
      label: item.name,
      children,
    };
  });
};

// 导出一个函数，用于生成区域数据

export const handleGoKnow = () => {

  wx.openOfficialAccountProfile({
    username: 'liaojian_China', // 此处填写公众号的微信号
    success: res => {
    },
    fail: res => {
    }
})
}


export const handleCompressImg = (tempFilePaths, quality): Promise<Array<String>> => {
  return new Promise(async (resolve, reject) => {
    try {
      // 将压缩操作封装为Promise数组
      const compressTasks = tempFilePaths.map(filePath =>
        new Promise((resolveCompress, rejectCompress) => {
          Taro.compressImage({
            src: filePath.url,
            quality,
            success: (res) => resolveCompress(res.tempFilePath),
            fail: rejectCompress
          });
        })
      );

      // 并行执行所有压缩任务
      const compressedPaths = await Promise.all(compressTasks);
      resolve(compressedPaths);
    } catch (error) {
      reject(error);
    }
  })

}

export const handleInitAgreementService = (type: String): Promise<{ content: Array<any>[] }> => {
  return new Promise(async (resolve, reject) => {
    const privacyRes = await handleAgreementService(type) as IResponseSuccess<IPrivacyResponse>
    if (privacyRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
      if (privacyRes.data.code === RESPONSE_CODE.SUCCESS) {
        resolve(privacyRes.data.data)
      } else {
        resolve({ content: [] })
      }

    } else {
      resolve({ content: [] })
    }
  })
}

export const handleInitAgreementPrivacy = (type: String): Promise<{ content: Array<any>[] }> => {
  return new Promise(async (resolve, reject) => {
    const privacyRes = await handleAgreementPrivacy(type) as IResponseSuccess<IPrivacyResponse>
    if (privacyRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
      if (privacyRes.data.code === RESPONSE_CODE.SUCCESS) {
        resolve(privacyRes.data.data)
      } else {
        resolve({ content: [] })
      }

    } else {
      resolve({ content: [] })
    }
  })
}
export const generateRegionData = (REGION_DATA: any[]) => {

  if (REGION_DATA && REGION_DATA.length > 0) { }
  const regionDataT: DataItem[] = formatData(REGION_DATA);
  // console.log(regionData)
  // code转汉字大对象
  const codeToTextT: { [key: string]: string } = {};
  REGION_DATA.forEach(province => {
    codeToTextT[province.code] = province.name;
    // 将省份的code和name存入codeToText对象中
    province.children.forEach(city => {
      // 遍历城市
      codeToTextT[city.code] = city.name;
      // 将城市的code和name存入codeToText对象中
      if (city.children && city.children.length > 0) {
        city.children.forEach(area => {
          // 遍历区域
          codeToTextT[area.code] = area.name;
        });
      }

    });
  });

  return { regionDataT, codeToTextT };
}
export async function subscribeMessage(tmplIds: string[]): Promise<ISubscribeMessagePromise> {
  // 模板ID
  

  // 1、获取设置状态
  const settings = (await Taro.getSetting({ withSubscriptions: true })).subscriptionsSetting || {}

  console.log('---设置状态---', settings)

  // 2、总开关
  if (!settings.mainSwitch) {// 返回结果，提示用户去设置中开启。可以使用弹框提示，　其中按钮使用<button open=type='openSetting'></button>引导用户
    return Promise.resolve({ content: '', status: false })
  }

  // 3、单个开关
  if (settings.itemSettings) {
    const notSubscribeTxt: string[] = []
    const yesSubscribeIds: string[] = []
    for (const item in settings.itemSettings) {
      if (settings.itemSettings[item] !== 'accept') {
        notSubscribeTxt.push(SUBSCRIBE_NOTICE[item])
        continue
      }
      yesSubscribeIds.push(item)
    }

    // 已订阅的消息增加次数 对应上边说的第4点，如果订阅多条，但是只允许接受一条消息，这里应增加允许消息的订阅次数，否则无法推送消息【遇到的坑】
    if (notSubscribeTxt.length && yesSubscribeIds.length) {
      Taro.requestSubscribeMessage({ tmplIds: yesSubscribeIds, entityIds: [] })
    }
    if (notSubscribeTxt.length) {
      return Promise.resolve({ content: ``, status: false })
    }
  }

  // 4、请求订阅
  return new Promise((resolve, reject) => {
    Taro.requestSubscribeMessage({
      tmplIds: tmplIds,
      entityIds: [],
      success: function (res) {
        resolve({ content: '', status: true })
      },
      fail: function (err) {
        resolve({ content: '', status: true })
      }
    })
  })
}

